#include "onlinemeeting.h"
#include "ui_onlinemeeting.h"
#include <QDebug>


OnlineMeeting::OnlineMeeting(QString meetingName, QString userName, QString ip, quint16 port, bool isCreator, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::OnlineMeeting), meetingName(meetingName), userName(userName), ip(ip), port(port), isCreator(isCreator)
{
    ui->setupUi(this);
    this->setWindowTitle(userName);
    ui->horizontalSlider->hide();
    ui->label_meetingName->setText(meetingName);
    this->setFixedSize(this->geometry().size());

    audio = new AudioHandler(userName, ip, port, this);
    connect(ui->btn_audio, &QPushButton::clicked, audio, &AudioHandler::onCbAudio);
    connect(audio, &AudioHandler::stateChange, this, &OnlineMeeting::onStateChanged);

    if (isCreator)
    {
        ui->btn_camera->show();
        ui->btn_finish->show();
//        ui->horizontalSlider->setValue(10);
        QListWidgetItem *item = new QListWidgetItem(userName);
        item->setTextAlignment(Qt::AlignCenter);
        ui->lw_onlineUser->addItem(item);
        camera = new CameraHandler(this);
        sender = new VideoSender(ip, port);
        socketThread = new QThread(this);
        sender->moveToThread(socketThread);

        connect(camera, &CameraHandler::videoUpdate, this, &OnlineMeeting::videoSet);
        connect(camera, &CameraHandler::sendVideo, sender, &VideoSender::sendVideo);
        connect(this, &OnlineMeeting::btnChang, camera, &CameraHandler::onBtnChange);
//        connect(ui->horizontalSlider, &QSlider::valueChanged, camera, &CameraHandler::setImageQuality);
        connect(camera, &CameraHandler::cameraChanged, this, &OnlineMeeting::onCameraChanged);
        connect(camera, &CameraHandler::getFps, this, &OnlineMeeting::onGetFps);
    }
    else
    {
        ui->btn_camera->hide();
        ui->btn_finish->hide();
        ui->horizontalSlider->hide();
        recever = new VideoRecever(ip, port);
        socketThread = new QThread(this);
        recever->moveToThread(socketThread);

        connect(socketThread, &QThread::started, recever, &VideoRecever::onReadyRead);
        connect(this, &OnlineMeeting::closeMeeting, recever, &VideoRecever::endTask);

        connect(recever, &VideoRecever::getFps, this, &OnlineMeeting::onGetFps);
        connect(recever, &VideoRecever::recvComplete, this, &OnlineMeeting::videoSet, Qt::BlockingQueuedConnection);

        timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &OnlineMeeting::onTimeout);
        timer->start(1000);
    }
    socketThread->start();
    qDebug() << "ip:" << ip << " port:" << port;
}

OnlineMeeting::~OnlineMeeting()
{
    delete ui;
    if (camera != nullptr)
    {
        delete camera;
        camera = nullptr;
    }
}

void OnlineMeeting::closeEvent(QCloseEvent *event)
{
//    event->ignore();
    if (recever != nullptr) recever->endTask();
    emit closeMeeting();
    messagePackage pack;
    if (isCreator)  pack.setType(messagePackage::ClearMeeting);
    else            pack.setType(messagePackage::QuitMeetintg);
    pack.setSender(userName);
    pack.setPort(port);
    messagePackage::sendMessage(&pack, socketHandler::getInstance()->getSocket());

    if (camera != nullptr)
    {
        delete camera;
        camera = nullptr;
    }
    if (socketThread != nullptr)
    {
        socketThread->quit();
        socketThread->wait();
    }
    event->accept();
}


void OnlineMeeting::on_btn_inviteUser_clicked()
{
    QString name = ui->le_inviteUser->text();
    if (name.isEmpty()) return ;
    ui->le_inviteUser->clear();
    messagePackage pack;
    pack.setType(messagePackage::InviteMeeting);
    pack.setSender(userName);
    pack.setReceiver(name);
    pack.setMeetingName(meetingName);
    pack.setIp(ip);
    pack.setPort(port);
    messagePackage::sendMessage(&pack, socketHandler::getInstance()->getSocket());
}

void OnlineMeeting::onUpdateMeeting(messagePackage pack)
{
    ui->lw_onlineUser->clear();
    for (auto user : pack.allUsers())
    {
        QListWidgetItem *item = new QListWidgetItem(user);
        item->setTextAlignment(Qt::AlignCenter);
        ui->lw_onlineUser->addItem(item);
    }
}


void OnlineMeeting::on_btn_finish_clicked()
{
    this->close();
}

void OnlineMeeting::on_videoUpdate(QImage image)
{
    QPixmap picture = QPixmap::fromImage(image); // 从QImage图片对象转成QPixmap格式图片对象
    ui->label_camera->setPixmap(picture);
}

void OnlineMeeting::on_horizontalSlider_valueChanged(int value)
{
    camera->setImageQuality(value);
}

void OnlineMeeting::on_btn_camera_clicked()
{
    emit btnChang();
}

void OnlineMeeting::onCameraChanged(QCamera::State state)
{
    if (state == QCamera::ActiveState)
    {
        ui->btn_camera->setText("关闭摄像头");
    }
    else
    {
        ui->btn_camera->setText("打开摄像头");
        ui->label_camera->clear();
//        sender->closeCamera();
    }
}

void OnlineMeeting::videoSet(QImage image)
{
    if (image.isNull())
    {
        return;
    }
    image = image.scaled(ui->label_camera->width(), ui->label_camera->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QPixmap picture = QPixmap::fromImage(image);
    ui->label_camera->setPixmap(picture);
    ++fps;
}

void OnlineMeeting::onGetFps(int value)
{
    if (value == 0)
    {
        ui->label_fps->clear();
        ui->label_camera->clear();
    }
    else {
        ui->label_fps->clear();
        QTimer::singleShot(150, this, [=](){
            ui->label_fps->setText(QString("FPS:%1").arg(value));
        });

    }
}

void OnlineMeeting::onStateChanged(QAudio::State state)
{
    if (state == QAudio::ActiveState)
    {
        ui->btn_audio->setText("关闭麦克风");
    }
    else
    {
        ui->btn_audio->setText("打开麦克风");
    }
}

void OnlineMeeting::onTimeout()
{
    onGetFps(fps);
    fps = 0;
}


